package de.farbstreich.tozen2.common;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.json.simple.parser.ContainerFactory;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/**
 * This class contains the information which will be send/received by client and server.
 * It decodes the information from JSON format( http://www.json.org )
 * @author mo
 * @return protocolMap
 */
public class DecodeJSONProtocol {

	/**
	 * protocolMap contains objects and arrays
	 * call value of key with protocolMap.get(key), key could be protocol type
	 * check if key(type) is in with contains(key)
	 */
	private Map protocolMap;

	public DecodeJSONProtocol(String msg) {
		decodeJSON(msg.trim());
	}
	
	public Map getProtocolMap() {
		return protocolMap;
	}
	
	/**
	 * @param inputMsg
	 * @return protocolMap: decoded inputMsg as Map
	 */
	public Map decodeJSON(String inputMsg) {
		JSONParser parser = new JSONParser();
		ContainerFactory containerFactory = new ContainerFactory(){
			public List creatArrayContainer() {
				return new LinkedList();
			}
			public Map createObjectContainer() {
				return new LinkedHashMap();
			}
		};         
		try{
			protocolMap = (Map)parser.parse(inputMsg, containerFactory);
		} catch(ParseException e) {
			System.out.println(e);
		}
		return protocolMap;
	}
	
}
